package com.zhiwang.xiaoqu.widget

import android.content.Context
import android.graphics.*
import android.text.Editable
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.EditText
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.ui.TextWatcherAdapter

class ClearableEditText : EditText {


    var clearIconBitmap: Bitmap

    var endMargin: Int = 0

    val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ClearableEditText)
        clearIconBitmap = BitmapFactory.decodeResource(
            resources,
            typedArray.getResourceId(R.styleable.ClearableEditText_clear_icon, 0)
        )
        endMargin = typedArray.getDimensionPixelSize(R.styleable.ClearableEditText_icon_margin_end, 0)
        typedArray.recycle()

        addTextChangedListener(object : TextWatcherAdapter() {

            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                invalidate()
            }
        })
    }


    var iconRect = RectF()

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        if (text.isEmpty().not()) {
            val left = measuredWidth - endMargin - clearIconBitmap.getScaledWidth(canvas) + 0f
            val top = (measuredHeight - clearIconBitmap.getScaledHeight(canvas)) / 2f

            iconRect.set(
                left,
                top,
                left + clearIconBitmap.getScaledWidth(canvas),
                top + clearIconBitmap.getScaledHeight(canvas)
            )
            canvas?.drawBitmap(clearIconBitmap, left, top, paint)
        }
    }


    var iconClicked = false

    override fun onTouchEvent(event: MotionEvent?): Boolean {

        if (text.isEmpty().not()) {
            when (event?.action) {
                MotionEvent.ACTION_DOWN -> {
                    val x = event.x
                    val y = event.y

                    iconClicked = iconRect.contains(x, y)
                }
                MotionEvent.ACTION_UP -> {
                    val x = event.x
                    val y = event.y
                    if (iconClicked && iconRect.contains(x, y))
                        setText("")
                    iconClicked = false
                }
            }
        }



        return super.onTouchEvent(event)
    }
}